import type {
  ApplyHeadingStyleOptions,
  HeadingLevel,
  HeadingTag,
  PlatformPageTypeValue,
  PlatformTypeValue,
  ThemeFutureOptions,
  ThemeType,
} from '../../../../types/interfaces'
import { TocEngine } from '../../../../module/page_enhancer/appearance/article_toc'
import {
  getAllTitleSelector,
  HEADING_STYLES,
  HEADING_TAG_LIST,
  logger,
  loggerDeduplicator,
  PAGE_ELEMENTS,
  PLATFORM_PAGE_TYPES,
  PROJECT_PREFIX,
  themeClassPrefix,
  TIME_UNITS,
} from '../../../../types/constants'
import { SYMBOLS,
} from '../../../../types/interfaces'
import { ICON_IDS } from '../../../icons/types/constants'
import { ToolKit } from '../../../utils/toolkit'
import { ThemeVarService } from '../theme_var/service'
import { BaseThemeService } from './base'

export abstract class BlogThemeService extends BaseThemeService {
  protected readonly articleSelector: string = 'article'
  private readonly checkHeadingTags: HeadingTag[] = HEADING_TAG_LIST
  readonly titleCustomSelector: string = `:is(${getAllTitleSelector()})`
  readonly applyHeadingStyleOptions: ApplyHeadingStyleOptions = {
    timeout: 0,
    condition: false,
  }

  protected declare elements: any
  abstract wrapperSelector: string // 最外层增加包裹，提高特异性
  abstract name: string
  abstract platformPageType: PlatformPageTypeValue
  protected futureOptions: ThemeFutureOptions = {
    followButton: false,
    copyRightButton: false,
    options: {
      followButtonClassName: undefined,
    },
  }

  protected excludedTitleElementsSelectors: string[] = []
  protected mermaidClassName: string = 'mermaid'
  private appliedTitleStyles: boolean = false
  private headingDetectionCache: { // 标题检测缓存
    existingHeadings: HeadingTag[] | null
    topThreeLevels: HeadingTag[] | null
    timestamp: number
  } = {
    existingHeadings: null,
    topThreeLevels: null,
    timestamp: 0,
  }

  private readonly CACHE_EXPIRY_MS: number = TIME_UNITS.COMMON.INTERVALS.FIVE_MINUTES // 缓存有效期（毫秒）- 推荐配置：5分钟

  protected constructor(platform: PlatformTypeValue) {
    super(platform)
    this.elements = PAGE_ELEMENTS[platform]
  }

  checkEnv(): void {
    super.checkEnv()

    this.checkArticleSelector()
  }

  initExcludedTitleElementsSelectors(selectors: string[]): void {
    this.excludedTitleElementsSelectors = [
      ...new Set([
        ...selectors,
        TocEngine.getInstance().sideMenuLoc.selector,
      ]),
    ]

    logger.debug(`[${this.name}] 排除标题选择器已更新: ${this.excludedTitleElementsSelectors.join(', ')}`)
  }

  private checkArticleSelector(): void {
    const $element = $(this.articleSelector)

    if ((!$element || !$element.length) && this.platformPageType === PLATFORM_PAGE_TYPES.BLOG.value)
      logger.warn(`[${this.name}] 文章选择器无效：${this.articleSelector}`)
  }

  protected updateElementStylesForTheme(): void {
    // 去掉表格内联宽度样式
    if (this.elements.CONTENT_TABLE && this.elements.CONTENT_TABLE.selector) {
      const $table = $(this.elements.CONTENT_TABLE.selector)
      $table.css('width', '')
      $table.find('tr td span').css('color', '')
      $table.find('tr, td').removeAttr('style')

      logger.debug(`[${this.name}] ${SYMBOLS.STATUS.REFRESH} 表格样式重置完成`)
    }
  }

  protected commonStyleVar(theme: ThemeType): string {
    return `
  /* 图表 */
  /* 甘特图 */
  --${PROJECT_PREFIX}-gantt-bg: ${this.getColorValue(theme, 'ganttBg')};
  --${PROJECT_PREFIX}-gantt-text: ${this.getColorValue(theme, 'ganttText')};
  --${PROJECT_PREFIX}-gantt-line-border: ${this.getColorValue(theme, 'ganttLineBorder')};
  --${PROJECT_PREFIX}-gantt-active-bg: ${this.getColorValue(theme, 'ganttActiveBg')};
  --${PROJECT_PREFIX}-gantt-active-text: ${this.getColorValue(theme, 'ganttActiveText')};
  --${PROJECT_PREFIX}-gantt-active-border: ${this.getColorValue(theme, 'ganttActiveBorder')};
  --${PROJECT_PREFIX}-gantt-done-bg: ${this.getColorValue(theme, 'ganttDoneBg')};
  --${PROJECT_PREFIX}-gantt-done-text: ${this.getColorValue(theme, 'ganttDoneText')};
  --${PROJECT_PREFIX}-gantt-done-border: ${this.getColorValue(theme, 'ganttDoneBorder')};
  --${PROJECT_PREFIX}-gantt-task-bg: ${this.getColorValue(theme, 'ganttTaskBg')};
  --${PROJECT_PREFIX}-gantt-task-text: ${this.getColorValue(theme, 'ganttTaskText')};
  --${PROJECT_PREFIX}-gantt-task-border: ${this.getColorValue(theme, 'ganttTaskBorder')};
  --${PROJECT_PREFIX}-gantt-today-border: ${this.getColorValue(theme, 'ganttTodayBorder')};
  /* 序列图 */
  --${PROJECT_PREFIX}-sequence-actor-bg: ${this.getColorValue(theme, 'sequenceActorBg')};
  --${PROJECT_PREFIX}-sequence-line-border: ${this.getColorValue(theme, 'sequenceLineBorder')};
  --${PROJECT_PREFIX}-sequence-line-text: ${this.getColorValue(theme, 'sequenceLineText')};
  --${PROJECT_PREFIX}-sequence-actor-border: ${this.getColorValue(theme, 'sequenceActorBorder')};
  --${PROJECT_PREFIX}-sequence-actor-text: ${this.getColorValue(theme, 'sequenceActorText')};
  --${PROJECT_PREFIX}-sequence-message-border-0: ${this.getColorValue(theme, 'sequenceMessageBorder0')};
  --${PROJECT_PREFIX}-sequence-message-border-1: ${this.getColorValue(theme, 'sequenceMessageBorder1')};
  --${PROJECT_PREFIX}-sequence-message-text: ${this.getColorValue(theme, 'sequenceMessageText')};
  --${PROJECT_PREFIX}-sequence-note-bg: ${this.getColorValue(theme, 'sequenceNoteBg')};
  --${PROJECT_PREFIX}-sequence-note-border: ${this.getColorValue(theme, 'sequenceNoteBorder')};
  --${PROJECT_PREFIX}-sequence-note-text: ${this.getColorValue(theme, 'sequenceNoteText')};
  /* LR图 */
  --${PROJECT_PREFIX}-lr-bg: ${this.getColorValue(theme, 'lrBg')};
  --${PROJECT_PREFIX}-lr-text: ${this.getColorValue(theme, 'lrText')};
  --${PROJECT_PREFIX}-lr-line-bg: ${this.getColorValue(theme, 'lrLineBg')};
  --${PROJECT_PREFIX}-lr-line-text: ${this.getColorValue(theme, 'lrLineText')};
  --${PROJECT_PREFIX}-lr-border: ${this.getColorValue(theme, 'lrBorder')};
  --${PROJECT_PREFIX}-lr-active: ${this.getColorValue(theme, 'lrActive')};
  --${PROJECT_PREFIX}-lr-done: ${this.getColorValue(theme, 'lrDone')};
  --${PROJECT_PREFIX}-label-bg: ${this.getColorValue(theme, 'labelBg')};
  --${PROJECT_PREFIX}-label-text: ${this.getColorValue(theme, 'labelText')};
  /* 流程图 */
  --${PROJECT_PREFIX}-flow-text: ${this.getColorValue(theme, 'flowText')};
  --${PROJECT_PREFIX}-flow-line-border: ${this.getColorValue(theme, 'flowLineBorder')};
  --${PROJECT_PREFIX}-flow-line-text: ${this.getColorValue(theme, 'flowLineText')};
  --${PROJECT_PREFIX}-flow-start-end-bg: ${this.getColorValue(theme, 'flowStartEndBg')};
  --${PROJECT_PREFIX}-flow-start-end-border: ${this.getColorValue(theme, 'flowStartEndBorder')};
  --${PROJECT_PREFIX}-flow-op-bg: ${this.getColorValue(theme, 'flowOpBg')};
  --${PROJECT_PREFIX}-flow-op-border: ${this.getColorValue(theme, 'flowOpBorder')};
  --${PROJECT_PREFIX}-flow-cond-bg: ${this.getColorValue(theme, 'flowCondBg')};
  --${PROJECT_PREFIX}-flow-cond-border: ${this.getColorValue(theme, 'flowCondBorder')};
  ${this.futureOptions?.copyRightButton
    ? `
  /* 版权 */
  --${PROJECT_PREFIX}-theme-copyright-button-text: ${this.getColorValue(theme, 'copyrightButtonText')};
  --${PROJECT_PREFIX}-theme-copyright-button-bg: ${this.getColorValue(theme, 'copyrightButtonBg')};
  --${PROJECT_PREFIX}-theme-copyright-button-bg-hover: ${this.getColorValue(theme, 'copyrightButtonBgHover')};
  --${PROJECT_PREFIX}-theme-copyright-button-border-left-color: ${this.getColorValue(theme, 'copyrightButtonBorderLeftColor')};
  --${PROJECT_PREFIX}-theme-copyright-button-shadow: ${this.getColorValue(theme, 'copyrightButtonShadow')};
  --${PROJECT_PREFIX}-theme-copyright-button-shadow-hover: ${this.getColorValue(theme, 'copyrightButtonShadowHover')};
  `
    : ''}
  
  ${this.futureOptions?.followButton && this.futureOptions?.options?.followButtonClassName
    ? `
  /* 关注按钮 */
  --${PROJECT_PREFIX}-follow-button-bg: ${this.getColorValue(theme, 'followButtonBg')};
  --${PROJECT_PREFIX}-follow-button-text: ${this.getColorValue(theme, 'followButtonText')};
`
    : ''}
`
  }

  protected platformStyleVar(_theme: ThemeType): string {
    return ''
  }

  getThemeStyles(theme: ThemeType): string {
    if (!this.elements) {
      loggerDeduplicator.error(`[${this.name}] 页面元素配置为空，无法获取主题样式`)
      return ''
    }

    const styles = `
/* ****************************************************** */
/*                   ${theme.toUpperCase()} 主题样式                        */
/* ****************************************************** */
/* ====================================================== */
/* ================= 一、样式变量定义区 ================== */
/* ====================================================== */
${this.getStyleVar(theme)}
/* ====================================================== */
/* ================= 二、全局页面样式 ==================== */
/* ====================================================== */
${this.getPageStyles(theme)}
/* ====================================================== */
/* ================= 三、主容器样式 ====================== */
/* ====================================================== */
${this.wrapperSelector} {
/* ------------------------------------------------------ */
/* ----------------- 3.1 基础布局样式 -------------------- */
/* ------------------------------------------------------ */
  ${this.getBaseStyles(theme)}
/* ------------------------------------------------------ */
/* ----------------- 3.2 核心视觉样式 -------------------- */
/* ------------------------------------------------------ */
  ${this.getMainStyles(theme)}
/* ------------------------------------------------------ */
/* ----------------- 3.3 视觉适配样式 -------------------- */
/* ------------------------------------------------------ */
  ${this.getPatchedStyles(theme)}
/* ------------------------------------------------------ */
/* ----------------- 3.4 问题修复样式 -------------------- */
/* ------------------------------------------------------ */
  ${this.getFixedStyles(theme)}
/* ------------------------------------------------------ */
/* ----------------- 3.5 公共组件样式 -------------------- */
/* ------------------------------------------------------ */
/* +++++++++++++++++ 3.5.1 作者样式 ++++++++++++++++++++++ */
  ${this.getAuthorStyles(theme)}
/* +++++++++++++++++ 3.5.2 主标题样式 ++++++++++++++++++++ */
  ${this.getTitleStyles(theme)}
/* +++++++++++++++++ 3.5.3 标签样式 ++++++++++++++++++++++ */
  ${this.getTagStyles(theme)}
/* +++++++++++++++++ 3.5.4 水平分割线样式 ++++++++++++++++ */
  ${this.getHrStyles(theme)}
/* +++++++++++++++++ 3.5.5 预格式化文本样式 ++++++++++++++ */
  ${this.getPreStyles(theme)}
/* +++++++++++++++++ 3.5.6 代码块样式 ++++++++++++++++++++ */
  ${this.getCodeStyles(theme)}
/* +++++++++++++++++ 3.5.7 标记样式 ++++++++++++++++++++++ */
  ${this.getMarkStyles(theme)}
/* +++++++++++++++++ 3.5.8 链接样式 ++++++++++++++++++++++ */
  ${this.getLinkStyles(theme)}
/* +++++++++++++++++ 3.5.9 图片样式 ++++++++++++++++++++++ */
  ${this.getImageStyles(theme)}
/* +++++++++++++++++ 3.5.10 视频样式 ++++++++++++++++++++++ */
  ${this.getVideoStyles(theme)}
/* +++++++++++++++++ 3.5.11 标题样式 +++++++++++++++++++++ */
  ${this.getHeadingStyles(theme)}
/* +++++++++++++++++ 3.5.12 表格样式 +++++++++++++++++++++ */
  ${this.getTableStyles(theme)}
/* +++++++++++++++++ 3.5.13 有序列表样式 ++++++++++++++++++ */
  ${this.getOlLiStyles(theme)}
/* +++++++++++++++++ 3.5.14 无序列表样式 ++++++++++++++++++ */
  ${this.getUlLiStyles(theme)}
/* +++++++++++++++++ 3.5.15 引用块样式 ++++++++++++++++++++ */
  ${this.getBlockQuoteStyles(theme)}
/* +++++++++++++++++ 3.5.16 复选框样式 ++++++++++++++++++++ */
  ${this.getCheckboxStyles(theme)}
/* +++++++++++++++++ 3.5.17 键盘样式 ++++++++++++++++++++++ */
  ${this.getKbdStyles(theme)}
/* +++++++++++++++++ 3.5.18 脚注样式 ++++++++++++++++++++++ */
  ${this.getFootnoteStyles(theme)}
/* +++++++++++++++++ 3.5.19 缩写样式 ++++++++++++++++++++++ */
  ${this.getAbbrStyles(theme)}
/* +++++++++++++++++ 3.5.20 流程图样式 ++++++++++++++++++++ */
  ${this.getMermaidStyles(theme)}
/* +++++++++++++++++ 3.5.21 其他样式 ++++++++++++++++++++++ */
  ${this.futureOptions?.followButton ? this.getFollowButtonStyles(theme) : ''}
  ${this.futureOptions?.copyRightButton ? this.getCopyrightButtonStyles(theme) : ''}
}
`
    return this.normalizeCssIndentation(styles)
  }

  getBaseStyles(_theme: ThemeType): string {
    const {
      CONTENT_CONTAINER,
      META_CONTAINER,
      TITLE_CONTAINER,
      INFO_CONTAINER,
      ARTICLE_COPYRIGHT_WRAPPER,
      ARTICLE_CONTENT,
      ARTICLE_HEADING,
    } = this.elements

    const BACKGROUND_RESET_SELECTORS = [
      META_CONTAINER?.selector,
      TITLE_CONTAINER?.selector,
      INFO_CONTAINER?.selector,
      ARTICLE_COPYRIGHT_WRAPPER?.selector,
      ARTICLE_CONTENT?.selector,
    ].filter(Boolean).join(',')

    const TEXT_COLOR_SELECTORS = [
      CONTENT_CONTAINER?.selector,
      ARTICLE_CONTENT?.selector,
    ].filter(Boolean).join(',')

    // 生成 CSS 规则
    return [
      CONTENT_CONTAINER?.selector && `
${CONTENT_CONTAINER.selector} {
  background-color: var(--${PROJECT_PREFIX}-theme-bg-base) !important;
  line-height: 1.8;
}
    `,

      BACKGROUND_RESET_SELECTORS && `
${BACKGROUND_RESET_SELECTORS} {
  background-color: unset !important;
}
    `,

      TEXT_COLOR_SELECTORS && `
${TEXT_COLOR_SELECTORS} {
  color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
}
    `,
      // 这里不使用 !important，避免影响标题样式的优先级
      ARTICLE_HEADING?.selector && `
${ARTICLE_HEADING.selector} {
  color: var(--${PROJECT_PREFIX}-theme-text-secondary);
}
    `,

    ].filter(Boolean).join('\n')
  }

  protected getMainStyles(_theme: ThemeType): string {
    return ''
  }

  protected getPageStyles(_theme: ThemeType): string {
    return ''
  }

  protected getPatchedStyles(_theme: ThemeType): string {
    return ''
  }

  protected getFixedStyles(_theme: ThemeType): string {
    return ''
  }

  protected getAuthorStyles(_theme: ThemeType): string {
    const { ARTICLE_AUTHOR } = this.elements

    if (!ARTICLE_AUTHOR || ARTICLE_AUTHOR.selector === '') {
      return ''
    }

    return `
${ARTICLE_AUTHOR.selector} {
  display: inline-flex !important;
  align-items: center;
  justify-content: center;
  text-decoration: none !important;
  position: relative;
  color: var(--${PROJECT_PREFIX}-theme-text-primary) !important;
  
  /* 作者图标 */
  &::before {
    content: "";
    display: inline-block;
    width: 16px;
    height: 16px;
    margin-right: 6px;
    background-image: var(${ThemeVarService.getInstance().generateIcon(ICON_IDS.role.author)});
    background-size: contain;
  }
}
`
  }

  protected getTitleStyles(_theme: ThemeType): string {
    const { ARTICLE_TITLE } = this.elements

    if (!ARTICLE_TITLE || ARTICLE_TITLE.selector === '') {
      return ''
    }

    return `
${ARTICLE_TITLE.selector} {
  color: var(--${PROJECT_PREFIX}-theme-text-primary) !important;
}
`
  }

  protected getTagStyles(theme: ThemeType): string {
    const { ARTICLE_TAG } = this.elements

    if (!ARTICLE_TAG || ARTICLE_TAG.selector === '') {
      return ''
    }

    return `
${ARTICLE_TAG.selector} {
  text-decoration: none !important;
  border-radius: 16px;
  line-height: 1.5;
  display: inline-flex !important;
  align-items: center;
  justify-content: center;
  border: var(--${PROJECT_PREFIX}-theme-tag-border) !important;
  color: var(--${PROJECT_PREFIX}-theme-tag-text) !important;
  ${theme === 'pink'
    ? `background: var(--${PROJECT_PREFIX}-theme-tag-bg) !important; text-shadow: 0 1px 1px rgba(0,0,0,0.1);`
    : `background-color: var(--${PROJECT_PREFIX}-theme-tag-bg) !important;`}
  box-shadow: var(--${PROJECT_PREFIX}-theme-tag-shadow) !important;
  margin-bottom: 5px;
  
  &:hover {
    transform: translateY(-1px);
    ${theme === 'pink'
      ? `background: var(--${PROJECT_PREFIX}-theme-tag-bg-hover) !important;`
      : `background-color: var(--${PROJECT_PREFIX}-theme-tag-bg-hover) !important;`}
    box-shadow: var(--${PROJECT_PREFIX}-theme-tag-shadow-hover) !important;
  }
  
  &::before {
    content: "#";
    margin-right: 2px;
    opacity: 0.8;
  }
}
`
  }

  protected getPreStyles(theme: ThemeType): string {
    const { CONTENT_PRE } = this.elements

    if (!CONTENT_PRE || CONTENT_PRE.selector === '') {
      return ''
    }

    return `
${CONTENT_PRE.selector} {
  margin-top: 4px !important;
  background-color: var(--${PROJECT_PREFIX}-theme-bg-base) !important;
  color: var(--${PROJECT_PREFIX}-theme-code-text-primary) !important;
  border-radius: 6px !important;
  border: 1px solid var(--${PROJECT_PREFIX}-theme-border-primary) !important;
  box-shadow: var(--${PROJECT_PREFIX}-theme-shadow-sm);
  overflow-x: auto !important;
  
  ${this.scrollStyles(theme)}
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: var(--${PROJECT_PREFIX}-theme-code-shadow-hover) !important;
  }
  
  &::before {
    background-color: transparent !important;
  }
  
  /* 代码块中的内联代码特殊处理 */
  code {
    color: inherit !important;
    background-color: transparent !important;
    border: none !important;
  }
  
  .opt-box {
    border-color: var(--${PROJECT_PREFIX}-theme-code-toolbar-divider) !important;
  }
  
  .code-language,.btn-code-notes,.hljs-button,.hljs-button::after,.code-run-btn,.hljs-ln-numbers,.pre-numbering {
    color: var(--${PROJECT_PREFIX}-theme-code-text-common) !important;
  }
  
  .pre-numbering {
    background-color: transparent !important;
    li {
      font-size: 13px !important;
    }
  }
  
  ${this.customPreInnerStyles(theme)}
}
${this.customPreOuterStyles(theme)}
`
  }

  protected customPreInnerStyles(_theme: ThemeType) {
    return ''
  }

  protected customPreOuterStyles(_theme: ThemeType) {
    return ''
  }

  protected getMarkStyles(_theme: ThemeType): string {
    const { CONTENT_MARK } = this.elements

    if (!CONTENT_MARK || CONTENT_MARK.selector === '') {
      return ''
    }

    return `
${CONTENT_MARK.selector} {
  background-color: var(--${PROJECT_PREFIX}-theme-mark-bg) !important;
  color: var(--${PROJECT_PREFIX}-theme-mark-text) !important;
  padding: 0.2em 0.4em;
  border-radius: 4px;
}
`
  }

  protected getImageStyles(theme: ThemeType): string {
    return super.getImageStyles(theme, this.articleSelector)
  }

  protected customImageStyles(_theme: ThemeType): string {
    return ''
  }

  protected getVideoStyles(_theme: ThemeType): string {
    return ''
  }

  protected getHeadingStyles(_theme: ThemeType): string {
    return `
/* 修复影响标题样式效果的情况 */
${this.articleSelector} {
  ${this.titleCustomSelector} :is(a, strong, span) {
    background-image: none !important;
    margin: unset !important;
    padding: unset !important;
  }
  .htmledit_views ${this.titleCustomSelector} :is(a, strong, span) {
    color: unset !important;
    font-weight: unset !important;
    border: none !important;
  }
  ${this.titleCustomSelector} code {
    margin: unset !important;
    padding: unset !important;
  }
  ${this.titleCustomSelector} br {
    display: none;
  }
}
`
  }

  protected getOlLiStyles(_theme: ThemeType): string {
    const { CONTENT_OL_LI } = this.elements

    if (!CONTENT_OL_LI || CONTENT_OL_LI.selector === '') {
      return ''
    }

    return `
${CONTENT_OL_LI.selector} {
  color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
  background-color: transparent !important;
}
`
  }

  protected getUlLiStyles(_theme: ThemeType): string {
    const { CONTENT_UL_LI } = this.elements

    if (!CONTENT_UL_LI || CONTENT_UL_LI.selector === '') {
      return ''
    }

    return `
${CONTENT_UL_LI.selector} {
  color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
  background-color: transparent !important;
}
`
  }

  protected getCheckboxStyles(_theme: ThemeType): string {
    return `
${this.articleSelector} {
  input[type=checkbox]:checked::before {
    background-color: var(--${PROJECT_PREFIX}-theme-primary) !important;
  }
}
`
  }

  protected getKbdStyles(_theme: ThemeType): string {
    return `
${this.articleSelector} {
  kbd {
    background-color: var(--${PROJECT_PREFIX}-theme-kbd-bg) !important;
    color: var(--${PROJECT_PREFIX}-theme-kbd-text) !important;
    margin-bottom: 5px !important;
  }
}
`
  }

  protected getFootnoteStyles(_theme: ThemeType): string {
    return `
${this.articleSelector} {
  /* 注脚内容 */
  .footnote-ref a {
    color: var(--${PROJECT_PREFIX}-theme-footnote-text) !important;
  }
  /* 注脚符号 */
  .footnotes .footnote-backref {
    color: var(--${PROJECT_PREFIX}-theme-footnote-text) !important;
  }
}
`
  }

  protected getAbbrStyles(_theme: ThemeType): string {
    return `
${this.articleSelector} {
  abbr {
    color: var(--${PROJECT_PREFIX}-theme-abbr-text) !important;
  }
}
`
  }

  getMermaidStyles(theme: ThemeType): string {
    return `
.${this.mermaidClassName} {
  background-color: unset !important;
  color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
  ${this.getGanttStyles(theme)}
  ${this.getSequenceDiagramStyles(theme)}
  ${this.getLrGraphStyles(theme)}
  ${this.getFlowChartStyles(theme)}
}
`
  }

  protected getGanttStyles(_theme: ThemeType): string {
    return ''
  }

  protected getSequenceDiagramStyles(_theme: ThemeType): string {
    return ''
  }

  protected getLrGraphStyles(_theme: ThemeType): string {
    return ''
  }

  protected getFlowChartStyles(_theme: ThemeType): string {
    return ''
  }

  protected getCopyrightButtonStyles(theme: ThemeType): string {
    const { ARTICLE_COPYRIGHT_BUTTON } = this.elements

    if (!ARTICLE_COPYRIGHT_BUTTON || ARTICLE_COPYRIGHT_BUTTON.selector === '') {
      return ''
    }

    return `
${ARTICLE_COPYRIGHT_BUTTON.selector} {
  display: inline-flex !important;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  text-decoration: none !important;
  font-weight: 600;
  padding: 0 5px;
  color: var(--${PROJECT_PREFIX}-theme-copyright-button-text) !important;
  ${theme === 'pink'
    ? `background: var(--${PROJECT_PREFIX}-theme-copyright-button-bg) !important;`
    : `background-color: var(--${PROJECT_PREFIX}-theme-copyright-button-bg) !important;`}
  border-left: 3px solid var(--${PROJECT_PREFIX}-theme-copyright-button-border-left-color);
  box-shadow: var(--${PROJECT_PREFIX}-theme-copyright-button-shadow);
  
  &:hover {
    ${theme === 'pink'
      ? `background: var(--${PROJECT_PREFIX}-theme-copyright-button-bg-hover) !important;`
      : `background-color: var(--${PROJECT_PREFIX}-theme-copyright-button-bg-hover) !important;`}
    box-shadow: var(--${PROJECT_PREFIX}-theme-copyright-button-shadow-hover);
  }
  
  &::before {
    content: "©";
    margin-right: 6px;
    font-size: 1.2em;
  }
  
  /* 去掉多余的竖线 */
  &:after {
    width: unset !important;
  }
}
`
  }

  protected getFollowButtonStyles(_theme: ThemeType): string {
    const followButtonClassName = this.futureOptions?.options?.followButtonClassName || undefined

    if (!followButtonClassName) {
      return ''
    }

    return `
.${followButtonClassName} {
  position: relative;
  border: none;
  border-radius: 6px;
  padding: 4px 16px;
  font-weight: 600;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  overflow: hidden;
  background: var(--${PROJECT_PREFIX}-follow-button-bg) !important;
  color: var(--${PROJECT_PREFIX}-follow-button-text) !important;
  margin-left: auto !important;
}
`
  }

  /**
   * 获取容器元素
   */
  private getContainerElements(): JQuery<HTMLElement> | undefined {
    const articleContainer = this.elements?.ARTICLE_CONTAINER

    if (!articleContainer) {
      if (this.platformPageType === PLATFORM_PAGE_TYPES.BLOG.value) {
        logger.warn(`[${this.name}] 未找到文章容器元素`)
      }
      return undefined
    }

    return $(articleContainer.selector)
  }

  /**
   * 智能应用标题样式
   * @param theme 当前主题
   */
  public applySmartHeadingStyles(theme: ThemeType): void {
    const $container = this.getContainerElements()

    if (!$container || !$container.length)
      return

    // 检查缓存有效性
    const cachedData = this.getCachedHeadingData()
    let existingHeadings: HeadingTag[]
    let topThreeLevels: HeadingTag[]

    if (cachedData) {
      logger.debug(`[${this.name}] ${SYMBOLS.UI.SAVE} 使用缓存的标题数据`)
      existingHeadings = cachedData.existingHeadings
      topThreeLevels = cachedData.topThreeLevels
    }
    else {
      logger.debug(`[${this.name}] ${SYMBOLS.UI.SEARCH} 重新检测标题结构`)
      existingHeadings = this.detectAllHeadings($container)
      topThreeLevels = this.getTopThreeLevels(existingHeadings)

      // 更新缓存
      this.updateHeadingCache(existingHeadings, topThreeLevels)
    }

    const shouldDelay = !this.applyHeadingStyleOptions.condition && !this.appliedTitleStyles
    const delayTime = shouldDelay ? this.applyHeadingStyleOptions.timeout : 0

    if (delayTime > 0)
      logger.info(`[${this.name}] ${SYMBOLS.TIME.HOURGLASS} 标题样式应用延迟 ${delayTime}ms`)

    const applyStyles = () => {
      // 处理前三个层级的标题
      topThreeLevels.forEach((tag, index) => {
        const level = (index + 1) as HeadingLevel // 转换为1-3级
        this.applyHeadingStyle($container, tag, level, theme)
      })

      // 处理剩余的标题
      const remainingHeadings = existingHeadings.filter(tag => !topThreeLevels.includes(tag))
      remainingHeadings.forEach((tag) => {
        this.applyHeadingStyle($container, tag, 4, theme) // 统一使用 level4 样式
      })

      this.appliedTitleStyles = true
    }

    ToolKit.async.delay(delayTime).then(applyStyles)
  }

  /**
   * 获取缓存的标题数据
   */
  private getCachedHeadingData(): { existingHeadings: HeadingTag[], topThreeLevels: HeadingTag[] } | null {
    const now = Date.now()
    const { existingHeadings, topThreeLevels, timestamp } = this.headingDetectionCache

    if (existingHeadings && topThreeLevels && (now - timestamp) < this.CACHE_EXPIRY_MS)
      return { existingHeadings, topThreeLevels }

    return null
  }

  /**
   * 更新标题检测缓存
   */
  private updateHeadingCache(existingHeadings: HeadingTag[], topThreeLevels: HeadingTag[]): void {
    this.headingDetectionCache = {
      existingHeadings: [...existingHeadings],
      topThreeLevels: [...topThreeLevels],
      timestamp: Date.now(),
    }
  }

  /**
   * 清除标题检测缓存
   */
  public clearHeadingCache(): void {
    this.headingDetectionCache = {
      existingHeadings: null,
      topThreeLevels: null,
      timestamp: 0,
    }
    logger.info(`[${this.name}] ${SYMBOLS.OTHERS.CLEAR} 标题检测缓存已清除`)
  }

  /**
   * 恢复所有标题的默认样式
   */
  public restoreDefaultHeadingStyles(): void {
    const $container = this.getContainerElements()

    if (!$container || !$container.length)
      return

    const $processedElements = $container.find(this.checkHeadingTags.join(','))
      .filter((_, el) => $(el).data('theme-processed') === true)

    if ($processedElements.length === 0) {
      logger.debug(`[${this.name}] ${SYMBOLS.STATUS.INFO} 没有需要恢复的标题样式`)
      return
    }

    $processedElements.each((_, el) => {
      const $el = $(el)

      $el.removeClass($el.data('title-classes'))
        .attr('class', $el.data('original-classes') || '')
        .removeData(['theme-processed', 'original-classes', 'title-classes'])
    })

    this.appliedTitleStyles = false
    this.clearHeadingCache()
    logger.info(`[${this.name}] ${SYMBOLS.ARROWS.BACK} 已恢复 ${$processedElements.length} 个标题的默认样式`)
  }

  /**
   * 检测所有存在的标题标签
   */
  private detectAllHeadings($container: JQuery): HeadingTag[] {
    const startTime = performance.now()

    const existingHeadings = this.checkHeadingTags.filter((tag) => {
      // 查找所有该类型的标题元素
      const $headings = $container.find(tag)

      // 如果没有排除选择器，直接检查是否存在
      if (this.excludedTitleElementsSelectors.length === 0)
        return $headings.length > 0

      // 排除被排除选择器匹配的元素及其子元素
      const excludedSelectors = this.getExcludedTitleSelector()
      const $filteredHeadings = $headings
        .filter((_, el) => !ToolKit.ui.element.isInSelectorList(el, excludedSelectors))

      return $filteredHeadings.length > 0
    })

    const duration = performance.now() - startTime
    logger.debug(`[${this.name}] ${SYMBOLS.TIME.STOPWATCH} 标题检测完成，耗时: ${duration.toFixed(2)}ms`)

    return existingHeadings
  }

  /**
   * 获取优先级最高的三个标题标签
   */
  private getTopThreeLevels(tags: HeadingTag[]): HeadingTag[] {
    // 按h1-h6自然顺序排序
    const sorted = [...tags].sort((a, b) =>
      Number.parseInt(a[1]) - Number.parseInt(b[1]),
    )

    // 取前三个（如果存在）
    return sorted.slice(0, 3)
  }

  /**
   * 获取排除标题选择器
   */
  getExcludedTitleSelector(): string[] {
    return this.excludedTitleElementsSelectors.length > 0
      ? this.excludedTitleElementsSelectors
      : []
  }

  /**
   * 应用具体标题样式
   */
  private applyHeadingStyle(
    $container: JQuery,
    originalTag: HeadingTag,
    targetLevel: HeadingLevel,
    theme: ThemeType,
  ): void {
    const style = HEADING_STYLES[targetLevel]
    const cssClass = `${style.className} ${themeClassPrefix}-${theme}`

    // 处理空排除选择器情况
    const excludedSelectors = this.getExcludedTitleSelector()

    const $targetElements = $container.find(originalTag)
      .filter((_, el) => {
        const $el = $(el)
        const isExcluded = ToolKit.ui.element.isInSelectorList(el, excludedSelectors)
        const text = $el.text().trim()
        return !isExcluded && text.length !== 0
      })

    if ($targetElements.length === 0) {
      logger.debug(`[${this.name}] ${SYMBOLS.UI.SEARCH} 未找到符合条件的 ${originalTag} 元素`)
      return
    }

    $targetElements.each((_, el) => {
      const $el = $(el)

      // 1. 标记处理状态
      $el.data('theme-processed', true)
        // 2.去掉之前的标题类
        .removeClass($el.data('title-classes'))
        // 3. 保存原始类
        .data('original-classes', $el.attr('class') || '')
        // 4. 保存当前标题类
        .data('title-classes', cssClass)
        // 5. 添加标题样式类
        .addClass(cssClass)

      // 6. 多行标题使用 block 布局
      if (ToolKit.ui.element.isMultilineText(el))
        ToolKit.dom.setElementCssAttribute($el, 'block')
    })

    logger.info(`[${this.name}] ${SYMBOLS.UI.BULLSEYE} 应用 ${originalTag} ${SYMBOLS.ARROWS.RIGHT} Level${targetLevel} 样式，影响 ${$targetElements.length} 个元素`)
  }
}
